package com.jy.wms.common.base;

import com.jy.wms.pojo.WmsAssistDelivery;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * HTTP 请求工具类
 *
 * @author : liii
 * @version : 1.0.0
 * @date : 2015/7/21
 * @see : TODO
 */
public class HttpUtil {
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 7000;
    
    private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
    
    static {
        // 设置连接池

        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 设置连接超时
        configBuilder.setConnectTimeout(MAX_TIMEOUT);
        // 设置读取超时
        configBuilder.setSocketTimeout(MAX_TIMEOUT);
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
        // 在提交请求之前 测试连接是否可用
        configBuilder.setStaleConnectionCheckEnabled(true);
        requestConfig = configBuilder.build();
    }

    /**
     * 发送 GET 请求（HTTP），不带输入数据
     * @param url
     * @return
     */
    public static String doGet(String url,String sessionId) {
        return doGet(url, new HashMap<String, Object>(),sessionId);
    }

    /**
     * 发送 GET 请求（HTTP），K-V形式
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url, Map<String, Object> params,String sessionId) {
        String apiUrl = url;
        StringBuffer param = new StringBuffer();
        int i = 0;
        for (String key : params.keySet()) {
            if (i == 0){
                param.append("?");
            }
            else{
                param.append("&");
            }
            param.append(key).append("=").append(params.get(key));
            i++;
        }
        apiUrl += param;
        String result = null;
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpPost = new HttpGet(apiUrl);
            System.out.println(apiUrl);
            httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);
            HttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("执行状态码 : " + statusCode);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送 POST 请求（HTTP），不带输入数据
     * @param apiUrl
     * @return
     */
    public static String doPost(String apiUrl) {
        return doPost(apiUrl, new HashMap<String, Object>());
    }

    /**
     * 发送 POST 请求（HTTP），K-V形式
     * @param apiUrl API接口URL
     * @param params 参数map
     * @return
     */
    public static String doPost(String apiUrl, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
        	//httpPost.setConfig(requestConfig);
            List<NameValuePair> pairList = new ArrayList<>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
                        .getValue().toString());
                pairList.add(pair);
            }
            //httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);
            httpPost.setHeader(new BasicHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.getMimeType()));
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            System.out.println(response.toString());
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }

    /**
     * 发送 POST 请求（HTTP），JSON形式
     * @param apiUrl
     * @param json json对象
     * @return
     */
    public static String doPost(String apiUrl, Object json) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
            //httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            //httpPost.setHeader("Cookie", "JSESSIONID="+sessionId);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine().getStatusCode());
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }
   /* public static void main(String[] args) {
//    	doGet("http://localhost:8071/safeGate/org/getOrgInfo/2","123");
    	//doPost("http://127.0.0.1:8070/ms-safety/org/getOrgInfo/2","FB675D096D671D527D245FD91CE12787");
        Map<String,Object> map = new HashMap<>();
        try {
            JSONObject content = new JSONObject();
            content.put("收件人姓名","小毅");
            content.put("订单号","10774");
            content.put("快递公司","申通快递");
            content.put("快递单号","110");
            String postData = "sign=87606B3B326C58F81884C1F6D4593CD4&userid=e4d2bc8335c44b09a107ab0b7df26faa&seller=大连双迪&" +
                    "tid=1528&phone=15726153280&outorder=&method=sendsms&content="+content.toString();
            map.put("sign","87606B3B326C58F81884C1F6D4593CD4");
            map.put("userid","e4d2bc8335c44b09a107ab0b7df26faa");
            map.put("seller","大连双迪");
            map.put("tid","1528");
            map.put("phone","15726153280");
            map.put("outorder","");

            map.put("content",content.toString());
            System.out.println("json:" + postData);
            String str = Send.SMS(postData,"http://apisms.kuaidi100.com:9502/sms/send.do");
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}*/

    /**
     * 申通根据重量计算快递费用
     * @param wmsAssistDelivery
     * @param zl
     * @return
     */
	public Integer computationalCosts(WmsAssistDelivery wmsAssistDelivery, Double zl){
        if(wmsAssistDelivery.getCs().equals("大连市")){
            return transportationAmount(zl,8,1,2);
        } else if (wmsAssistDelivery.getSf().equals("辽宁省")){
            return transportationAmount(zl,8,2,2);
        } else if (wmsAssistDelivery.getSf().equals("黑龙江省") || wmsAssistDelivery.getSf().equals("吉林省") ||
                wmsAssistDelivery.getSf().equals("北京市") || wmsAssistDelivery.getSf().equals("天津市")) {
            return transportationAmount(zl, 8, 3, 2);
        } else if(wmsAssistDelivery.getSf().equals("湖北省")){
            return transportationAmount(zl, 10, 3, 2);
        } else if(wmsAssistDelivery.getSf().equals("山东省") || wmsAssistDelivery.getSf().equals("江苏省") ||
                wmsAssistDelivery.getSf().equals("上海市") || wmsAssistDelivery.getSf().equals("浙江省") || wmsAssistDelivery.getSf().equals("安徽省")){
            return transportationAmount(zl, 10, 4, 2);
        } else if(wmsAssistDelivery.getSf().equals("河南省") || wmsAssistDelivery.getSf().equals("湖北省") || wmsAssistDelivery.getSf().equals("广东省")){
            return transportationAmount(zl, 10, 5, 2);
        } else if(wmsAssistDelivery.getSf().equals("山西省") || wmsAssistDelivery.getSf().equals("陕西省") || wmsAssistDelivery.getSf().equals("四川省") ||
                wmsAssistDelivery.getSf().equals("重庆市") || wmsAssistDelivery.getSf().equals("湖南省") ){
            return transportationAmount(zl, 10, 6, 2);
        } else if(wmsAssistDelivery.getSf().equals("内蒙古") || wmsAssistDelivery.getSf().equals("江西省") || wmsAssistDelivery.getSf().equals("福建省")){
            if(zl <= 1){
                return transportationAmount(zl, 15, 10, 1);
            }else {
                return transportationAmount(zl, 18, 6, 2);
            }
        } else if(wmsAssistDelivery.getSf().equals("贵州省") || wmsAssistDelivery.getSf().equals("云南省")){
            if(zl <= 1){
                return transportationAmount(zl, 15, 10, 1);
            }else{
                return transportationAmount(zl, 18, 7, 2);
            }
        } else if(wmsAssistDelivery.getSf().equals("广西省")){
            if(zl <= 1){
                return transportationAmount(zl, 15, 10, 1);
            }else {
                return transportationAmount(zl, 20, 7, 2);
            }
        } else if(wmsAssistDelivery.getSf().equals("海南省")){
            if(zl <= 1){
                return transportationAmount(zl, 18, 13, 1);
            }else {
                return transportationAmount(zl, 22, 8, 2);
            }
        } else if(wmsAssistDelivery.getSf().equals("宁夏省") || wmsAssistDelivery.getSf().equals("甘肃省") || wmsAssistDelivery.getSf().equals("青海省")){
            return transportationAmount(zl, 18, 14, 1);
        } else if(wmsAssistDelivery.getSf().equals("新疆") || wmsAssistDelivery.getSf().equals("西藏")){
            return transportationAmount(zl, 20, 20, 1);
        } else {
            return 0;
        }
    }

    /**
     * 申通计算运输金额
     * @param zl 总重量
     * @param sz 首重金额
     * @param xz 续重金额
     * @param szgj 首重公斤
     * @return
     */
    public Integer transportationAmount (Double zl,Integer sz,Integer xz,Integer szgj){
        //小于等于0.05 向下取整
        Double xiaoshu=Double.parseDouble(String.format("%.2f", zl-Math.floor(zl)));
        if(xiaoshu<=0.05){
            if(Math.floor(zl) <= szgj){
                return sz;
            }else{
                return sz + xz * ((int)Math.floor(zl - szgj));
            }
        }else {
            if(Math.ceil(zl) <= szgj){
                return sz;
            }else{
                return sz + xz * ((int)Math.ceil(zl - szgj));
            }
        }


    }

    /**
     * 圆通根据重量计算快递费用
     * @param wmsAssistDelivery
     * @param zl
     * @return
     */
    public Integer ytComputationalCosts(WmsAssistDelivery wmsAssistDelivery,Double zl){
        if(wmsAssistDelivery.getCs().equals("大连市")||wmsAssistDelivery.getSf().equals("辽宁省")){
            return ytTransportationAmount(zl,5,2,3);
        }  else if (wmsAssistDelivery.getSf().equals("黑龙江省") || wmsAssistDelivery.getSf().equals("吉林省")
                || wmsAssistDelivery.getSf().equals("北京市") || wmsAssistDelivery.getSf().equals("天津市")
                || wmsAssistDelivery.getSf().equals("山东省")|| wmsAssistDelivery.getSf().equals("江苏省")
                || wmsAssistDelivery.getSf().equals("浙江省") || wmsAssistDelivery.getSf().equals("上海市")
                || wmsAssistDelivery.getSf().equals("安徽省")|| wmsAssistDelivery.getSf().equals("河北省")) {
            return ytTransportationAmount(zl, 5, 4, 3);
        } else if(wmsAssistDelivery.getSf().equals("四川省")||wmsAssistDelivery.getSf().equals("重庆市")
                ||wmsAssistDelivery.getSf().equals("湖南省") ||wmsAssistDelivery.getSf().equals("江西省")
                ||wmsAssistDelivery.getSf().equals("云南省") ||wmsAssistDelivery.getSf().equals("广西省")
                ||wmsAssistDelivery.getSf().equals("海南省")
                ){
            return ytTransportationAmount(zl, 5, 6, 3);
        }  else if(wmsAssistDelivery.getSf().equals("内蒙古") || wmsAssistDelivery.getSf().equals("贵州省")){
            return ytTransportationAmount(zl, 10, 6, 1);
        } else if(wmsAssistDelivery.getSf().equals("甘肃省") ){
                return ytTransportationAmount(zl, 10, 8, 1);
        }else if(wmsAssistDelivery.getSf().equals("青海省") ){
            return ytTransportationAmount(zl, 15, 10, 1);
        }else if(wmsAssistDelivery.getSf().equals("宁夏省") ){
            return ytTransportationAmount(zl, 15, 8, 1);
        }else if(wmsAssistDelivery.getSf().equals("新疆") ){
            return ytTransportationAmount(zl, 20, 20, 1);
        }  else if(wmsAssistDelivery.getSf().equals("西藏")){
                return ytTransportationAmount(zl, 20, 18, 1);
        } else {
            return 0;
        }
    }
    /**
     * 圆通计算运输金额
     * @param zl 总重量
     * @param sz 首重金额
     * @param xz 续重金额
     * @param szgj 首重公斤
     * @return
     */
    public Integer ytTransportationAmount (Double zl,Integer sz,Integer xz,Integer szgj){
        String zls=String.valueOf(zl);
        Integer a=Integer.parseInt(zls.substring(zls.indexOf(".")+1,zls.indexOf(".")+2));
        if(a>=1){
            if(Math.ceil(zl)<=szgj){
               return sz;
            }else{
                return  sz+((int)Math.ceil(zl)-1)*xz;
            }
        }else {
            if(Math.floor(zl)<=szgj){
                return sz;
            }else{
                return  sz+((int)Math.floor(zl)-1)*xz;
            }
        }
    }

    public static void main(String[] args) {
        Double zl=4.05;
        String zls=String.valueOf(zl);
        Integer a=Integer.parseInt(zls.substring(zls.indexOf(".")+1,zls.indexOf(".")+2));


        System.out.println(Math.floor(zl));

       Double xiaoshu= Double.parseDouble(String.format("%.2f", zl-Math.floor(zl)));
        System.out.println(xiaoshu<=0.05);
        // Integer a=Integer.valueOf(zls.substring(zls.indexOf("."),zls.indexOf(".")+1));
       // System.out.println(a);
    }

    /**
     * 发运订单发送短信
     * @param lxr 联系人
     * @param lxdh 联系电话
     * @param ddh 订单号
     * @param kddh 快递单号
     * @param cyslb 承运商 （3：申通 6： 圆通）
     * @return map type  boolean 成功信息 msg 失败信息 type=false才有的
     * @throws Exception
     */
    public static Map<String,Object> message(String lxr,String lxdh,String ddh,String kddh,String cyslb ){
        Map<String,Object> map = new HashMap<>();
        try {
            JSONObject content = new JSONObject();
            content.put("收件人姓名",lxr);
            content.put("订单号",ddh);
            if(cyslb.equals("3")){//申通
                content.put("快递公司",ckfhInfo.fydd_dx_kdgs.getType());
            }else if(cyslb.equals("6")){//圆通
                content.put("快递公司",ckfhInfo.fydd_dx_kdgs2.getType());
            }
            content.put("快递单号",kddh);
            String postData = "sign="+ ckfhInfo.fydd_dx_sign.getType()+
                    "&userid="+ ckfhInfo.fydd_dx_userid.getType()+
                    "&seller="+  ckfhInfo.fydd_dx_seller.getType()+
                    "&tid="+ckfhInfo.fydd_dx_tid.getType()+
                    "&phone="+lxdh+"&outorder=&method=sendsms&content="+content.toString();
            JSONObject ret = JSONObject.fromObject(Send.SMS(postData,"http://apisms.kuaidi100.com:9502/sms/send.do"));
            if(ret.get("status").toString().equals("1")){
                map.put("type",true);
                map.put("msg","短信发送中");
            }else{
                log.debug(ret.get("msg").toString());
                map.put("type",false);
                map.put("msg",ret.get("msg").toString());

            }
        } catch (Exception e) {
            map.put("type",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }
}